package com.mohan.system.manage.realm;

import com.mohan.system.manage.entity.Menu;
import com.mohan.system.manage.entity.User;
import com.mohan.system.manage.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class SystemRealm extends AuthorizingRealm {
    @Resource
    private IUserService userService;

    /**
     * 自定义授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("进入了授权方法");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前用户身份信息
        User principal = (User) principalCollection.getPrimaryPrincipal();
        List<String> roles = userService.userRoles(principal.getUsername());
        List<Menu> roleInfo = userService.getUserMenu(Boolean.TRUE);
        List<String> roleInfoString = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(roleInfo)) {
            for (Menu menu : roleInfo) {
                roleInfoString.add(menu.getPerms());
            }
        }
        log.info("当前角色的信息...{}",roles);
        // 存储角色
        if (!CollectionUtils.isEmpty(roles)) {
            info.addRoles(roles);
        }

        // 存储接口权限
        if (!CollectionUtils.isEmpty(roleInfoString)) {
            info.addStringPermissions(roleInfoString);
        }
        return info;
    }

    /**
     * 自定义登录认证的方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取用户身份信息
        String name = authenticationToken.getPrincipal().toString();
        User user = userService.getUserInfoByUserName(name);

        // 返回数据完成封装
        return new SimpleAuthenticationInfo(
                user,
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                getName());
    }
}
